package com.haobangs.imms.task;

import cn.hutool.core.date.DateUtil;
import com.haobangs.imms.domain.Factory;
import com.haobangs.imms.service.IFactoryService;
import com.haobangs.imms.smsUtils.AliyunSmsService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.json.JSONObject;

import java.time.Duration;
import java.util.Date;
import java.util.List;

/**
 * @Author HaoBangs
 * @Date 2024年 04月 7日
 * @Description 定时任务
 **/
@Slf4j
@Component
public class AccessTask {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Scheduled(cron = "0 0 8 ? * MON")
    public void smsTimer() throws JSONException {
        String url = "https://open.ys7.com/api/lapp/token/get";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
        map.add("appKey", "c92a946c023641afabf69316b95f24c9");
        map.add("appSecret", "8a94d1719fb46154a6d3372d8ff8ed37");

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);

        if (response.getStatusCode() == HttpStatus.OK) {

            // 解析 JSON 响应并提取 access_token
            String responseBody = response.getBody();

            // 将JSON字符串转换为JSONObject
            JSONObject jsonObject = new JSONObject(responseBody);

            // 提取access_token字段的值
            String accessToken = jsonObject.getString("accessToken");
            stringRedisTemplate.opsForValue().set("YinshiaccessToken", accessToken, Duration.ofDays(7));


        } else {
            // 处理错误情况
            log.info("未能获得萤石的accesstoken");

        }
    }

}
